<?php
/**
 * @category   Epic
 * @package    Epic_Controller
 * @author     Epic Core Team <rukanhitokiri@gmail.com>
 */
class Epic_Controller_Router_Route
{
	/**
     * Singleton instance
     * @var Epic_Controller_Router_Route
     */
	private static $_instance = null;
	
	/**
     * Request object
     * @var Epic_Controller_Request_Abstract
     */
	private $_request = null;
	
	/**
     * Singleton instance
     *
     * @return Epic_Controller_Router_Route
     */
	public static function getInstance() 
	{
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
	}
	
    /**
     * Enforce singleton; disallow cloning
     *
     * @return void
     */
    private function __clone() {}

    /**
     * Set the Request object retrive from Front
     * 
     * @param $request Epic_Controller_Request_Abstract
     * $return Epic_Controller_Router_Route
     */
    public function setRequest($request)
    {
        $this->_request = $request;
        return $this;
    }

    /**
     * Retrieve request object
     *
     * @return Epic_Controller_Request_Abstract
     */
    public function getRequest()
    {
        return $this->_request;
    }
    
    /**
	 * Route constructor used to set the necessary parameters
 	 * (module, controller, action) to the Request object
	 * 
     * @return void
     */
    public function route()
    {
        $fragments = explode('/', trim($_SERVER['REQUEST_URI'], '/')); 
        
        $pathInfo = pathinfo($_SERVER['PHP_SELF']);
        if($pathInfo['dirname'] != '/') {
			array_shift($fragments);
    	}
	
		$config = Epic::getRegistry()->get('config');
		
    	// set the module
		if(!empty($fragments[0])) {
			$this->getRequest()->setModuleName($fragments[0]);
		} else {
			$this->getRequest()->setModuleName($config->getDefaultModule());
		}
		
		// set the controller
		if(!empty($fragments[1])) {
			$this->getRequest()->setControllerName($fragments[1]);
		} else {
			$this->getRequest()->setControllerName($config->getDefaultController());
		}
		
		// set the action
		if(!empty($fragments[2])) {
			// Be sure to remove the params and take proper action name
			$action = explode('?', $fragments[2]);	
			$this->getRequest()->setActionName($action[0]);
		} else {
			$this->getRequest()->setActionName($config->getDefaultAction());
		}
    }
}